package com.yoga.manager.app.impl;

import com.yoga.common.appexception.AppErrorCodeEnum;
import com.yoga.common.appexception.AppException;
import com.yoga.common.bo.SendSmsBO;
import com.yoga.common.enumcommon.SmsBusinessEnum;
import com.yoga.manager.app.CaptchaCodeManager;
import com.yoga.manager.app.SmsManager;
import com.yoga.manager.smsUtil.CodeUtil;
import com.yoga.manager.uitl.JsonUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * Created by chenjin on 2019/7/9.
 */
@Component
public class CaptchaCodeManagerImpl implements CaptchaCodeManager {
    private final Logger logger = LoggerFactory.getLogger(CaptchaCodeManagerImpl.class);

    @Resource(name="stringRedisTemplate")
    private ValueOperations<String,String> vops;

    @Resource
    private SmsManager smsManager;

    @Value("${sendSmsStatus}")
    private Integer sendSmsStatus;


    @Override
    public boolean addToCache(String phoneNumber, SmsBusinessEnum captchaTypeEnum) throws AppException {
        try {
            if (StringUtils.isEmpty(phoneNumber)|| captchaTypeEnum==null){
                logger.error("手机号码为空或者code为空 CaptchaCodeManagerImpl.addToCache phoneNumber{},captchaTypeEnum{}",phoneNumber,captchaTypeEnum.toString());
                throw new AppException(AppErrorCodeEnum.PHONE_IS_NULL);
            }
            String key=new StringBuffer().append(captchaTypeEnum.name()).append("_").append(phoneNumber).toString();

            String rediscode= vops.get(key);
            logger.info("rediscode:--->>>{}，captchaTypeEnum:{}", rediscode,captchaTypeEnum.name());

            if (StringUtils.isNotEmpty(rediscode)){
                logger.error("验证码未超时1分钟，不能发送 CaptchaCodeManagerImpl.addToCache phoneNumber{},captchaTypeEnum{},rediscode:{}",phoneNumber,captchaTypeEnum.toString(),rediscode);
                throw new AppException(AppErrorCodeEnum.AUTH_CAPTCHA_FREQUENCY);
            }
            String code= CodeUtil.getCode(captchaTypeEnum);
            logger.info("code:--->>>{}，captchaTypeEnum:{}", code,captchaTypeEnum.name());
            if (sendSmsStatus==0) {
                SendSmsBO sendSmsBO = new SendSmsBO();
                sendSmsBO.setCode(code);
                Boolean aBoolean = smsManager.sendSms(phoneNumber, captchaTypeEnum, sendSmsBO);
                if (!aBoolean) {
                    logger.error("系统错误 发送短信失败 smsService.sendSms phoneNumber{},captchaTypeEnum{},sendSmsBO:{}", phoneNumber, captchaTypeEnum.toString(), JsonUtil.toJson(sendSmsBO));
                    throw new AppException(AppErrorCodeEnum.SYSTEM_ERROR);
                }
            }
            vops.set(key,code,2, TimeUnit.MINUTES);
            return true;
        } catch (AppException e) {
            throw e;
        }catch (Exception e){
            logger.error("手机号码为空或者code为空 CaptchaCodeManagerImpl.addToCache phoneNumber{},captchaTypeEnum{}, e{}",phoneNumber,captchaTypeEnum.toString(),e);
            throw new AppException(AppErrorCodeEnum.SYSTEM_ERROR);
        }
    }



    @Override
    public boolean validation(String phoneNumber, String code, SmsBusinessEnum captchaTypeEnum) throws AppException {

        try {
            if (StringUtils.isEmpty(phoneNumber)|| StringUtils.isEmpty(code) || captchaTypeEnum==null){
                logger.error("手机号码为空或者code为空 CaptchaCodeManagerImpl.validation phoneNumber{},code{},captchaTypeEnum{}",phoneNumber,code,captchaTypeEnum.toString());
                throw new AppException(AppErrorCodeEnum.PHONE_IS_NULL);
            }

            String key=new StringBuffer().append(captchaTypeEnum.name()).append("_").append(phoneNumber).toString();

            String redisCode= vops.get(key);
            if (StringUtils.isEmpty(redisCode)){
                logger.error("验证码已过期 CaptchaCodeManagerImpl.validation phoneNumber{},code{},captchaTypeEnum{}",phoneNumber,code,captchaTypeEnum.toString());
                throw new AppException(AppErrorCodeEnum.AUTH_CAPTCHA_OVERDUE);
            }

            if (!code.equals(redisCode)){
                logger.error("验证码验证错误 CaptchaCodeManagerImpl.validation phoneNumber{},code{},redisCode{},captchaTypeEnum{}",phoneNumber,code,redisCode,captchaTypeEnum.toString());
                throw new AppException(AppErrorCodeEnum.AUTH_CAPTCHA_ERROR);
            }

        }catch (AppException e){
            throw e;
        }catch (Exception e) {
            logger.error("系统错误 CaptchaCodeManagerImpl.validation phoneNumber{},code{},captchaTypeEnum{},e{}",phoneNumber,code,captchaTypeEnum.toString(),e);
            throw new AppException(AppErrorCodeEnum.SYSTEM_ERROR);
        }
        return true;
    }
}
